<?php

namespace app\admin\service;

use app\admin\model\BoxYunGoods;

/**
 * 云挂机服务类
 */
class BoxYunGoodsService extends BaseService
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new BoxYunGoods();
    }


    public function getList(): array
    {
        $params = request()->param();
        $page  = request()->param('page', 1);
        $limit = request()->param('limit', 10);
        $where = [];
        if(!empty($params['name'])){
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        if(!empty($params['status'])){
            $where[] = ['status', '=', $params['status']];
        }
        if(!empty($params['time_range'][0]) && !empty($params['time_range'][1])){
            $where[] = ['up_time', 'between', [$params['time_range'][0], $params['time_range'][1]]];
        }
        $list  = $this->model->where('mark', '=', 1)->where($where)->page($page, $limit)->order('id', 'desc')->select();
        //返回结果
        $count = $this->model->where('mark', '=', 1)->count();
        return array (
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $list,
            "count" => $count,
        );
    }

    /**
     * 添加或编辑
     * @return mixed
     * @since 2021/6/9
     * @author ZhangXuanNeng
     */
    public function edit()
    {
        // 参数
        $data = request()->param();
        if(!empty($data['id'])){
            $add_stock = $data['add_stock'] ?? 0;
            $result = $this->model->where('id', '=', $data['id'])->field('stock,remaining_stock')->find();
            $data['stock'] = $result['stock'] + $add_stock;
            $data['remaining_stock'] = $result['remaining_stock'] + $add_stock;

        }else{
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['remaining_stock'] = $data['stock'] ?? 0;
        }

//        if($data['price'] > $data['original_price']){
//            return message('售价不能大于原价',0);
//        }

        $data['up_time'] = $data['time_range'][0] ?? date('Y-m-d H:i:s');
        $data['down_time'] = $data['time_range'][1];

        return parent::edit($data); // TODO: Change the autogenerated stub
    }

    public function delete()
    {
        return parent::delete(); // TODO: Change the autogenerated stub
    }
}